package com.cango.student.http;

import com.alibaba.fastjson.JSON;
import com.cango.student.SerializationUtil;
import com.cango.student.WsResult;
import okhttp3.OkHttpClient;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class RestTemplateOkhttpSample {

    public static void main(String[] args) throws Exception {



        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30,TimeUnit.SECONDS)
                .retryOnConnectionFailure(true).build();
        OkHttp3ClientHttpRequestFactory okHttp3ClientHttpRequestFactory = new OkHttp3ClientHttpRequestFactory(client);

        RestTemplate restTemplate = new RestTemplate(okHttp3ClientHttpRequestFactory);

        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        messageConverters.add(new MyConverter());

        String url = "http://10.43.23.211:8080/zl/binaryBodyResponse";
        WsResult from = new WsResult();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "binary/octet-stream");
        HttpEntity<byte[]> formEntity = new HttpEntity<>(SerializationUtil.serialize(from), headers);


        long start = System.currentTimeMillis();
        for (int i = 50; i > 0; i--) {

            ResponseEntity<WsResult> entity = restTemplate.postForEntity(url, formEntity, WsResult.class, new Object());

            System.out.println(JSON.toJSONString(entity.getBody()));

        }
        System.out.println("cost is:" + (System.currentTimeMillis() - start));

    }

}
